package com.example.demo.util;

import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ImageUtil {
	

	private ImageUtil() {}

//	private static final ImageUtil iu = new ImageUtil();
//	
//	public static ImageUtil getInstance() {
//		return iu;
//	}

//	private static ImageUtil instance = null;
//	public static ImageUtil getInstance() {
//		if(instance == null) {
//			instance = new ImageUtil();
//		}
//		return instance;
//	}
	
	private static final int WIDTH = 200;
	private static final int HEIGHT = 40;
	
	private static final char[] characters = {
			'a','b','c','d','e','f','g','h',
			'i','j','k','l','m','n','o','p',
			'q','r','s','t','u','v','w','x',
			'y','z','0','1','2','3','4','5',
			'6','7','8','9'
	};

	public static String getRandomStr(int length) {

		StringBuilder sb = new StringBuilder();

		Random r = new Random();
		for(int i=0; i<length; i++) {

			int index = r.nextInt(characters.length);

			char c = characters[index];
			if(index % 3 == 0) {
				c = Character.toUpperCase(c);
			}
			sb.append(c);
		}
		return sb.toString();
	}
	
	public static BufferedImage generateCapture(HttpSession session) {

		BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

		Graphics g = bi.getGraphics();

		g.setColor(Color.LIGHT_GRAY);

		g.fillRect(0, 0, WIDTH, HEIGHT);

		Random r = new Random();

		String capture = getRandomStr(5);
		session.setAttribute("capture", capture);
		for(int i=0; i<capture.length(); i++) {
			char c = capture.charAt(i);
			g.setColor(getRandomColor(r));
			g.drawString(Character.toString(c), i*20+r.nextInt(10), 10 + r.nextInt(20));
		}

//		g.setFont(font);
//		new Font("宋体", Font.PLAIN, 20);
		g.dispose();
		return bi;
	}
	
	private static Color getRandomColor(Random random) {

		int rRange = Color.LIGHT_GRAY.getRed();
		int r = random.nextInt(rRange);

		int gRange = Color.LIGHT_GRAY.getGreen();
		int g = random.nextInt(gRange);

		int bRange = Color.LIGHT_GRAY.getBlue();
		int b = random.nextInt(bRange);
		return new Color(r,g,b);
	}
	
	public static void main(String[] args) {
		String s = getRandomStr(10);
		System.out.println(s);
	}
	
}
